package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.LikeVideoApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.mongo.VideoLike;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private LikeVideoApi likeVideoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 上传视频
     * @param videoThumbnail 封面图片文件
     * @param videoFile 视频文件
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        if (videoFile.isEmpty() || videoThumbnail.isEmpty()){
            throw new BusinessException(ErrorResult.videoError());
        }
        //1.将视频上传到FastDFS，获取访问URL
        String filename = videoFile.getOriginalFilename(); // eg: abc.mp4
        filename = filename.substring(filename.lastIndexOf(".") + 1); // mp4
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();

        //2.将封面图片上传到阿里云OSS,获取访问的URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //3.构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火"); //视频文案，客户端还没有实现，这里写死即可
        //4.调用API保存数据
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)){ //如果保存的视频的id是空，则保存失败
            throw new BusinessException(ErrorResult.videoSaveError());
        }
    }

    /**
     * 分页查询视频列表 --- 通过SpringCache对分页查询视频列表进行优化
     * @Cacheable：
     *          value：指定命名空间
     *          key：定义key的规则
     *          T(包名.类名).方法名 ---SpringEl当中调用静态方法的规则
     */
    @Cacheable(
            value = "videos",
            key ="T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize" ) //key的规则：userid_page_pagesize
    public PageResult queryVideoList(Integer page, Integer pagesize) {

        //1.如果redis数据不存在,调用api去mongo中查询数据
        List<Video> list = videoApi.queryVideoList(page, pagesize);

        //2.提取视频列表中的所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);

        //3.查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);

        //4.构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if (info != null){
                VideoVo vo = VideoVo.init(info, video);

                //从redis中获取，当前用户是否已经关注了视频发布者
                String key = Constants.FOCUS_USER+UserHolder.getUserId();
                String hashKey = String.valueOf(video.getUserId());
                if (redisTemplate.opsForHash().hasKey(key,hashKey)){
                    vo.setHasFocus(1);
                }

                vos.add(vo);
            }

        }
        return new PageResult(page,pagesize,0l,vos);
    }

    //分页查询视频列表
/*    public PageResult queryVideoList(Integer page, Integer pagesize) {

        //1.查询redis数据
        String redisKey= Constants.VIDEOS_RECOMMEND +UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);

        //2.判断redis数据是否存在,判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0; //记录redis当中一共有多少页数据
        if (!StringUtils.isEmpty(redisValue)){ //3.如果redis数据存在，根据VID查询数据
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总数
            if ((page-1)*pagesize < values.length){
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e->Long.valueOf(e))
                        .collect(Collectors.toList());
                //调用API根据VID数组查询动态数据
                list = videoApi.findVideosByVids(vids);
            }
            redisPages = PageUtil.totalPage(values.length,pagesize);
        }

        //4.如果redis数据不存在,mongo中分页查询视频数据
        if (list.isEmpty()){
            //page的计算规则， 传入的页码 -- (page - redis查询的总页数)
            list = videoApi.queryVideoList(page - redisPages,pagesize);
        }

        //5.提取视频列表中的所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);

        //6.查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);

        //7.构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if (info != null){
                VideoVo vo = VideoVo.init(info, video);

                //从redis中获取，当前用户是否已经关注了视频发布者
                String key = Constants.FOCUS_USER+UserHolder.getUserId();
                String hashKey = String.valueOf(video.getUserId());
                if (redisTemplate.opsForHash().hasKey(key,hashKey)){
                    vo.setHasFocus(1);
                }

                vos.add(vo);
            }

        }
        return new PageResult(page,pagesize,0l,vos);
    }*/

    //关注视频作者
    public void userFocus(Long followUserId) {

        //构造数据
        FocusUser focusUser = new FocusUser(null,UserHolder.getUserId(),followUserId,System.currentTimeMillis());
        //调用api保存关注数据到mongo
        videoApi.saveUserFocus(focusUser);

        //同时保存数据到redis
        String key = Constants.FOCUS_USER+UserHolder.getUserId();
        String hashkey = String.valueOf(followUserId);
        redisTemplate.opsForHash().put(key,hashkey,"1");
    }

    //取消关注视频作者
    public void userUnFocus(Long followUserId) {
        //删除redis中的缓存数据
        String key = Constants.FOCUS_USER+UserHolder.getUserId();
        String hashkey = String.valueOf(followUserId);
        redisTemplate.opsForHash().delete(key,hashkey);

        //删除mongo中的数据
        videoApi.deleteUserFocus(UserHolder.getUserId(),followUserId);

    }

    //点赞（对喜欢的视频点赞）
    @CacheEvict(value = "videos")
    public void like(Long videoId) {
        //1. 调用api查询用户是否已点赞
        Boolean hasLike = likeVideoApi.hasLike(UserHolder.getUserId(),videoId);
        //2. 如果已经点赞,抛出异常
        if (hasLike){
            throw new BusinessException(ErrorResult.likeError());
        }
        //3. 调用api保存数据到mongo
        VideoLike videoLike = new VideoLike(null,UserHolder.getUserId(),videoId,System.currentTimeMillis());
        likeVideoApi.save(videoLike);
    }
}
